package com.flyco.modules.stm.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flyco.modules.stm.entity.*;
import com.flyco.modules.stm.service.*;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.vo.StmStoreMessagePage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

 /**
 * @Description: 店铺通知表
 * @Author: flyco
 * @Date:   2022-10-09
 * @Version: V1.0
 */
@Api(tags="店铺通知表")
@RestController
@RequestMapping("/f/stm/stmStoreMessage")
@Slf4j
public class StmStoreMessageController {
	@Autowired
	private IStmStoreMessageService stmStoreMessageService;
	@Autowired
	private IStmStoreMessageReService stmStoreMessageReService;
	@Autowired
	private IStmStoreMessageReadService stmStoreMessageReadService;
	@Autowired
	private IStmStoreMessageAttachmentService stmStoreMessageAttachmentService;
     @Autowired
     private IStmStoreInfoService stmStoreInfoService;
	/**
	 * 分页列表查询
	 *
	 * @param stmStoreMessage
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "店铺通知表-分页列表查询")
    @ApiOperation(value="店铺通知表-分页列表查询", notes="店铺通知表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StmStoreMessage stmStoreMessage,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<StmStoreMessage> queryWrapper = QueryGenerator.initQueryWrapper(stmStoreMessage, req.getParameterMap());
		Page<StmStoreMessage> page = new Page<StmStoreMessage>(pageNo, pageSize);
		IPage<StmStoreMessage> pageList = stmStoreMessageService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param stmStoreMessagePage
	 * @return
	 */
	@AutoLog(value = "店铺通知表-添加")
	@ApiOperation(value="店铺通知表-添加", notes="店铺通知表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody StmStoreMessagePage stmStoreMessagePage) {
       StmStoreMessage stmStoreMessage = new StmStoreMessage();
		BeanUtils.copyProperties(stmStoreMessagePage, stmStoreMessage);
		stmStoreMessageService.save(stmStoreMessage);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param stmStoreMessagePage
	 * @return
	 */
	@AutoLog(value = "店铺通知表-编辑")
	@ApiOperation(value="店铺通知表-", notes="店铺通知表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StmStoreMessagePage stmStoreMessagePage) {
		StmStoreMessage stmStoreMessage = new StmStoreMessage();
		BeanUtils.copyProperties(stmStoreMessagePage, stmStoreMessage);
		stmStoreMessageService.updateById(stmStoreMessage);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "店铺通知表-通过id删除")
	@ApiOperation(value="店铺通知表-通过id删除", notes="店铺通知表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		stmStoreMessageService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "店铺通知表-批量删除")
	@ApiOperation(value="店铺通知表-批量删除", notes="店铺通知表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.stmStoreMessageService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "店铺通知表-通过id查询")
	@ApiOperation(value="店铺通知表-通过id查询", notes="店铺通知表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		StmStoreMessage stmStoreMessage = stmStoreMessageService.getById(id);
		return Result.ok(stmStoreMessage);
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	 * 通过主表id查询店铺通知关联表
	 *
  	 * @param stmStoreMessageRe
	 * @return
	 */
	@AutoLog(value = "店铺通知关联表-通过主表id查询")
    @ApiOperation(value="店铺通知关联表-通过主表id查询", notes="店铺通知关联表-通过主表id查询")
	@GetMapping(value = "/listStmStoreMessageReByMainId")
	public Result<?> listStmStoreMessageReByMainId(StmStoreMessageRe stmStoreMessageRe,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(stmStoreMessageRe.getMessageId()!=null) {
            QueryWrapper<StmStoreMessageRe> queryWrapper = QueryGenerator.initQueryWrapper(stmStoreMessageRe, req.getParameterMap());
            Page<StmStoreMessageRe> page = new Page<StmStoreMessageRe>(pageNo, pageSize);
            IPage<StmStoreMessageRe> pageList =  stmStoreMessageReService.page(page, queryWrapper);
            if (pageList.getTotal() > 0) {
                List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
                Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
                pageList.getRecords().forEach(re -> {
                    if (oConvertUtils.isNotEmpty(re.getStoreId())) {
                        if (storeInfoMaps.containsKey(re.getStoreId())) {
                            re.setStoreId_dictText(storeInfoMaps.get(re.getStoreId()));
                        }
                    }
                });
            }
            return Result.ok(pageList);
        }else{
            return Result.ok();
        }
    }
	
	/**
     * 添加店铺通知关联表
     *
     * @param stmStoreMessageRe
     * @return
     */
    @AutoLog(value = "店铺通知关联表-添加")
    @ApiOperation(value="店铺通知关联表-添加", notes="店铺通知关联表-添加")
    @PostMapping(value = "/addStmStoreMessageRe")
    public Result<?> addStmStoreMessageRe(@RequestBody StmStoreMessageRe stmStoreMessageRe) {
        stmStoreMessageReService.save(stmStoreMessageRe);
        return Result.ok("添加店铺通知关联表成功！");
    }
    
    /**
     * 编辑店铺通知关联表
     *
     * @param stmStoreMessageRe
     * @return
     */
    @AutoLog(value = "店铺通知关联表-编辑")
    @ApiOperation(value="店铺通知关联表-编辑", notes="店铺通知关联表-编辑")
    @PutMapping("/editStmStoreMessageRe")
    public Result<?> editStmStoreMessageRe(@RequestBody StmStoreMessageRe stmStoreMessageRe) {
        stmStoreMessageReService.updateById(stmStoreMessageRe);
        return Result.ok("编辑店铺通知关联表成功！");
    }
    
    /**
     * 通过id删除店铺通知关联表
     *
     * @param id
     * @return
     */
    @AutoLog(value = "店铺通知关联表-通过id删除")
    @ApiOperation(value="店铺通知关联表-通过id删除", notes="店铺通知关联表-通过id删除")
    @DeleteMapping(value = "/deleteStmStoreMessageRe")
    public Result<?> deleteStmStoreMessageRe(@RequestParam(name = "id", required = true) String id) {
       stmStoreMessageReService.removeById(id);
        return Result.ok("删除店铺通知关联表成功！");
    }
	
	/**
     * 批量删除店铺通知关联表
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "店铺通知关联表-批量删除")
    @ApiOperation(value="店铺通知关联表-批量删除", notes="店铺通知关联表-批量删除")
    @DeleteMapping(value = "/deleteBatchStmStoreMessageRe")
    public Result<?> deleteBatchStmStoreMessageRe(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.stmStoreMessageReService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    
	/**
	 * 通过主表id查询用户通知已读标记表
	 *
  	 * @param stmStoreMessageRead
	 * @return
	 */
	@AutoLog(value = "用户通知已读标记表-通过主表id查询")
    @ApiOperation(value="用户通知已读标记表-通过主表id查询", notes="用户通知已读标记表-通过主表id查询")
	@GetMapping(value = "/listStmStoreMessageReadByMainId")
	public Result<?> listStmStoreMessageReadByMainId(StmStoreMessageRead stmStoreMessageRead,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(stmStoreMessageRead.getMessageId()!=null) {
            QueryWrapper<StmStoreMessageRead> queryWrapper = QueryGenerator.initQueryWrapper(stmStoreMessageRead, req.getParameterMap());
            Page<StmStoreMessageRead> page = new Page<StmStoreMessageRead>(pageNo, pageSize);
            IPage<StmStoreMessageRead> pageList =  stmStoreMessageReadService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.ok();
        }
    }
	
	/**
     * 添加用户通知已读标记表
     *
     * @param stmStoreMessageRead
     * @return
     */
    @AutoLog(value = "用户通知已读标记表-添加")
    @ApiOperation(value="用户通知已读标记表-添加", notes="用户通知已读标记表-添加")
    @PostMapping(value = "/addStmStoreMessageRead")
    public Result<?> addStmStoreMessageRead(@RequestBody StmStoreMessageRead stmStoreMessageRead) {
        stmStoreMessageReadService.save(stmStoreMessageRead);
        return Result.ok("添加用户通知已读标记表成功！");
    }
    
    /**
     * 编辑用户通知已读标记表
     *
     * @param stmStoreMessageRead
     * @return
     */
    @AutoLog(value = "用户通知已读标记表-编辑")
    @ApiOperation(value="用户通知已读标记表-编辑", notes="用户通知已读标记表-编辑")
    @PutMapping("/editStmStoreMessageRead")
    public Result<?> editStmStoreMessageRead(@RequestBody StmStoreMessageRead stmStoreMessageRead) {
        stmStoreMessageReadService.updateById(stmStoreMessageRead);
        return Result.ok("编辑用户通知已读标记表成功！");
    }
    
    /**
     * 通过id删除用户通知已读标记表
     *
     * @param id
     * @return
     */
    @AutoLog(value = "用户通知已读标记表-通过id删除")
    @ApiOperation(value="用户通知已读标记表-通过id删除", notes="用户通知已读标记表-通过id删除")
    @DeleteMapping(value = "/deleteStmStoreMessageRead")
    public Result<?> deleteStmStoreMessageRead(@RequestParam(name = "id", required = true) String id) {
       stmStoreMessageReadService.removeById(id);
        return Result.ok("删除用户通知已读标记表成功！");
    }
	
	/**
     * 批量删除用户通知已读标记表
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "用户通知已读标记表-批量删除")
    @ApiOperation(value="用户通知已读标记表-批量删除", notes="用户通知已读标记表-批量删除")
    @DeleteMapping(value = "/deleteBatchStmStoreMessageRead")
    public Result<?> deleteBatchStmStoreMessageRead(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.stmStoreMessageReadService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }


     /**
      * 通过主表id查询用户通知附件记表
      *
      * @param stmStoreMessageAttachment
      * @return
      */
     @AutoLog(value = "用户通知附件表-通过主表id查询")
     @ApiOperation(value="用户通知附件表-通过主表id查询", notes="用户通知附件表-通过主表id查询")
     @GetMapping(value = "/listStmStoreMessageAttachmentByMainId")
     public Result<?> listStmStoreMessageAttachmentByMainId(StmStoreMessageAttachment stmStoreMessageAttachment,
                                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                            HttpServletRequest req) {
         if(stmStoreMessageAttachment.getMessageId()!=null) {
             QueryWrapper<StmStoreMessageAttachment> queryWrapper = QueryGenerator.initQueryWrapper(stmStoreMessageAttachment, req.getParameterMap());
             Page<StmStoreMessageAttachment> page = new Page<StmStoreMessageAttachment>(pageNo, pageSize);
             IPage<StmStoreMessageAttachment> pageList =  stmStoreMessageAttachmentService.page(page, queryWrapper);
             return Result.ok(pageList);
         }else{
             return Result.ok();
         }
     }

     /**
      * 添加用户通知附件记表
      *
      * @param stmStoreMessageAttachment
      * @return
      */
     @AutoLog(value = "用户通知附件表-添加")
     @ApiOperation(value="用户通知附件表-添加", notes="用户通知附件表-添加")
     @PostMapping(value = "/addStmStoreMessageAttachment")
     public Result<?> addStmStoreMessageAttachment(@RequestBody StmStoreMessageAttachment stmStoreMessageAttachment) {
         stmStoreMessageAttachmentService.save(stmStoreMessageAttachment);
         return Result.ok("添加用户通知附件成功！");
     }

     /**
      * 编辑用户通知附件记表
      *
      * @param stmStoreMessageAttachment
      * @return
      */
     @AutoLog(value = "用户通知附件表-编辑")
     @ApiOperation(value="用户通知附件表-编辑", notes="用户通知附件表-编辑")
     @PutMapping("/editStmStoreMessageAttachment")
     public Result<?> editStmStoreMessageAttachment(@RequestBody StmStoreMessageAttachment stmStoreMessageAttachment) {
         stmStoreMessageAttachmentService.updateById(stmStoreMessageAttachment);
         return Result.ok("编辑用户通知附件成功！");
     }

     /**
      * 通过id删除用户通知附件记表
      *
      * @param id
      * @return
      */
     @AutoLog(value = "用户通知附件表-通过id删除")
     @ApiOperation(value="用户通知附件表-通过id删除", notes="用户通知附件表-通过id删除")
     @DeleteMapping(value = "/deleteStmStoreMessageAttachment")
     public Result<?> deleteStmStoreMessageAttachment(@RequestParam(name = "id", required = true) String id) {
         stmStoreMessageAttachmentService.removeById(id);
         return Result.ok("删除用户通知附件成功！");
     }

     /**
      * 批量删除用户通知附件记表
      *
      * @param ids
      * @return
      */
     @AutoLog(value = "用户通知附件表-批量删除")
     @ApiOperation(value="用户通知附件表-批量删除", notes="用户通知附件表-批量删除")
     @DeleteMapping(value = "/deleteBatchStmStoreMessageAttachment")
     public Result<?> deleteBatchStmStoreMessageAttachment(@RequestParam(name = "ids", required = true) String ids) {
         if (ids == null || "".equals(ids.trim())) {
             return Result.error("参数不识别！");
         }
         this.stmStoreMessageAttachmentService.removeByIds(Arrays.asList(ids.split(",")));
         return Result.ok("批量删除成功！");
     }
    

    /**
    * 导出excel
    *
    * @param request
    * @param stmStoreMessage
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StmStoreMessage stmStoreMessage) {
      // Step.1 组装查询条件
      QueryWrapper<StmStoreMessage> queryWrapper = QueryGenerator.initQueryWrapper(stmStoreMessage, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<StmStoreMessagePage> pageList = new ArrayList<StmStoreMessagePage>();
      List<StmStoreMessage> stmStoreMessageList = stmStoreMessageService.list(queryWrapper);
      for (StmStoreMessage temp : stmStoreMessageList) {
          StmStoreMessagePage vo = new StmStoreMessagePage();
          BeanUtils.copyProperties(temp, vo);
          List<StmStoreMessageRe> stmStoreMessageReList = stmStoreMessageReService.selectByMainId(temp.getId());
          vo.setStmStoreMessageReList(stmStoreMessageReList);
          List<StmStoreMessageRead> stmStoreMessageReadList = stmStoreMessageReadService.selectByMainId(temp.getId());
          vo.setStmStoreMessageReadList(stmStoreMessageReadList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "店铺通知表");
      mv.addObject(NormalExcelConstants.CLASS, StmStoreMessagePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("店铺通知表数据", "导出人:"+sysUser.getRealname(), "店铺通知表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<StmStoreMessagePage> list = ExcelImportUtil.importExcel(file.getInputStream(), StmStoreMessagePage.class, params);
              for (StmStoreMessagePage page : list) {
                  StmStoreMessage po = new StmStoreMessage();
                  BeanUtils.copyProperties(page, po);
                  stmStoreMessageService.saveMain(po, page.getStmStoreMessageReList(),page.getStmStoreMessageReadList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
